<template>
  <div>
    <AplidForm ref="formRef" v-bind="BaseFormConfig" v-model="formModel" @submit="onSubmit"> </AplidForm>
  </div>
</template>

<script setup lang="ts">
import apiMod from '@/apiMod'
import { BaseFormConfig } from '../../config'
import { getAreaObj } from '@/utils/util'
import { useCommonStore } from '@/stores/common'
import { useOperate } from '@/views/datacenter/hooks/useConfig'
const { getValue } = useOperate(2)
const { setTempParams ,setLoading} = useCommonStore()

const nowRowData: any = inject('nowRowData')
const emit = defineEmits(['submit'])

const formModel = ref({})
const formRef = ref()
let baseData = markRaw({})
// 数据变更处理
const onSubmit = (form, done) => {
  const areaObj: any = getAreaObj(form.areas)
  const areaNameObj: any = getAreaObj(form.areas_name)

  const nowAreasObj: any = getAreaObj(form.nowAreas, 'now')
  const nowAreasNamesObj: any = getAreaObj(form.nowAreasNames, 'now')

  const params = {
    ...form,
    ...areaObj,
    ...areaNameObj,
    ...nowAreasObj,
    ...nowAreasNamesObj,
  }

  // 处理变更字段
  let changeColumnsBase = BaseFormConfig.column.filter((item) => item.changeField)

  let changeData = []
  changeColumnsBase.map((item) => {
    const tempBefore = baseData[item.propName || item.prop]
    const tempAfter = params[item.propName || item.prop]
    if (tempBefore !== tempAfter) {
      changeData.push({
        label: item.label,
        before: getValue(tempBefore, item),
        after: getValue(tempAfter, item),
      })
    }
  })

  const emptyObj = {
    code: undefined,
    areas_name: undefined,
    areas: undefined,
    nowAreas: undefined,
    nowAreasNames: undefined,
  }
  const changeObj = {
    data: changeData,
    dataChangeContentList: [
      {
        changeBefore: {
          ...baseData,
          ...emptyObj,
        },
        changeAfter: {
          ...params,
          ...emptyObj,
        },
        changeData: {
          ...params,
          ...emptyObj,
        },
        changeType: '养老服务组织-养老机构',
        code: 3013,
      },
    ],
  }
  setTempParams({
    organizationName: params.organizationName,
    name: params.organizationName,
    creditCode: params.creditCode,
    nowChange: changeObj,
  })
  emit('submit', changeObj)
  done()
}

const onSave = () => {
  formRef.value!.onSubmit()
}
// 数据回显
const getInitData = () => {
  setLoading()
  apiMod.view_dpServiceOrgBase_view(nowRowData.id).then((res) => {
    const area: any = getAreaObj(res.data, '', 'get')
    const nowArea: any = getAreaObj(res.data, 'now', 'get')
    const data = {
      ...res.data,
      areas: area.areaIds,
      areas_name: area.names,
      nowAreas: nowArea.areaIds,
      nowAreasNames: nowArea.names,
    }
    formModel.value = data
    baseData = Object.freeze(JSON.parse(JSON.stringify(data)))
    setLoading()
  })
}
defineExpose({
  onSave,
})

onMounted(() => {
  getInitData()
})
</script>

<style scoped></style>
